import json
from tonclient.types import ClientConfig,ParamsOfParse
from tonclient.client import TonClient
from flask import Flask, request, jsonify
from flask_cors import CORS
import requests


# 初始化TON客户端
config = ClientConfig()
config.network.endpoints = [
    # 'https://testnet.ton.dev',
    # 'https://testnet.tonhubapi.com', 
    # 'https://testnet.toncenter.com/api/v2'
    'https://mainnet.ton.dev',
    'https://toncenter.com/api/v2/jsonRPC'
]
config.network.network_retries_count = 5
config.network.query_timeout = 60000
tonclient = TonClient(config = config)

app = Flask(__name__)
CORS(app)
@app.route('/ton/parse_boc', methods=['POST'])
def parse_boc():
    try:
        # 从请求中获取JSON数据
        data = request.get_json()

        # 获取BOC数据
        boc = data.get('boc', None)
        playerId = data.get('playerId')
        prop_id = data.get('prop_id')

        if not boc:
            return jsonify({'error': 'No BOC provided'}), 400

        # 处理BOC数据，例如调用TON客户端解析BOC
        parsed_boc = tonclient.boc.parse_message(ParamsOfParse(boc = boc))
        # print(parsed_boc.parsed)

        if parsed_boc.parsed['status'] == 3 or parsed_boc.parsed['status'] == 5:
            url = "http://127.0.0.1:25365"
            kbe_data={
                'playerId': playerId,
                'boc': boc,
                'prop_id': prop_id,
                'result': parsed_boc.parsed['status']
            }
            kbe_json = json.dumps(kbe_data)
            response = requests.post(url,data=kbe_json)
            if response.status_code == 200:
                return jsonify({'status': 'success'})
            else:
                return jsonify({'error': 'Failed to send data to KBEngine'}), 500
        else:
            return jsonify({'error': 'transaction failed'}), 500
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port = 5050)
